package org.zerg.controller.web;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zerg.dto.FileDto;
import org.zerg.entity.Category;
import org.zerg.entity.Product;
import org.zerg.service.CategoryService;

@Controller
@RequestMapping("/category")
public class CategoryWebController {

	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private HttpSession session;
	
	@RequestMapping("/list")
	public String getCategoryList(){
		List<Category> list = categoryService.categoryAll();
		session.setAttribute("list", list);
		return "/category";
	}
	
	@RequestMapping("/inser")
	public String inserCategory(FileDto dto,@RequestParam("name")String name){
		categoryService.inserCategory(dto,name);
		return "redirect:/category/list";
	}
	
	@RequestMapping("/modify")
	public String modifyCategory(FileDto dto,@RequestParam("name")String name,@RequestParam("id")int id){
		if(dto==null||dto.getImgFile()==null||dto.getImgFile().getSize()<=0){
			categoryService.modifyCategoryNoFile(name,id);
		}else{
			categoryService.modifyCategory(dto,name,id);
		}
		return "redirect:/category/list";
	}
	
	@RequestMapping("/delete")
	public String deleteCategory(@RequestParam("id")int id){
		categoryService.deleteCategory(id);
		return "redirect:/category/list";
	}
	
	@RequestMapping("/detaile")
	public String categoryDetaileById(@RequestParam("id")int id){
		List<Product> list = categoryService.getProductByCate(id);
		List<Category> list2 = categoryService.categoryAll();
		session.setAttribute("list", list);
		session.setAttribute("list2", list2);
		return "/category_detaile";
	}
	
	@RequestMapping("/mo")
	public String modifyProductOnCate(@RequestParam("id")int id,@RequestParam("pid")int pid){
		categoryService.modifyProductOnCate(id,pid);
		return "redirect:/category/detaile?id="+pid;
	}
	
	@RequestMapping("/isname")
	@ResponseBody
	public boolean isName(@RequestParam("name")String name){
		boolean result = categoryService.isName(name);
		return result;
	}
	
}
